package com.prp.gwt.server;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.prp.bo.RegisterAuthMailSender;
import com.prp.bo.User;
import com.prp.db.po.UserInformation;
import com.prp.gwt.client.ClientConstants;
import com.prp.gwt.client.entry.EntryService;

public class EntryServiceImpl extends RemoteServiceServlet implements
		EntryService {

	private static final long serialVersionUID = -3094854988424509276L;

	@Override
	public int signIn(String email, String password) {
		if (email == null)
			return ClientConstants.SIGNIN_NOUSER;
		if (password == null)
			return ClientConstants.SIGNIN_PASSERROR;
		if (!User.hasUser(email))
			return ClientConstants.SIGNIN_NOUSER;
		if (!User.checkPassword(email, password))
			return ClientConstants.SIGNIN_PASSERROR;
		if (!User.isActivated(email))
			return ClientConstants.SIGNIN_NOTACTIVATED;
		UserInformation info = User.getUser(email);
		getThreadLocalRequest().getSession().setAttribute(ClientConstants.ATTR_USER,
				info.getUserId());
		if (info.getIdentity() == 1)
			return ClientConstants.SIGNIN_ADMIN;
		else if (info.getIdentity() == 2)
			return ClientConstants.SIGNIN_ROOT;
		else
			return ClientConstants.SIGNIN_USER;
	}

	@Override
	public boolean retrievePassword(final String email) {
		if(!User.hasUser(email))
			return false;
		Runnable r = new Runnable() {
			@Override
			public void run() {
				RegisterAuthMailSender.sendRetrievePasswordMail(email);
			}
		};
		new Thread(r).start();
		return true;
	}
}
